package com.knife.news.manage.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import com.knife.news.logic.SiteService;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.object.Template;
import com.knife.operation.Discoverer;
import com.knife.util.CommUtil;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;

public class GenerateTemplateManageAction extends ManageAction {
	SiteService siteDAO = SiteServiceImpl.getInstance();
	
	public Page doInit(WebForm form, Module module) {
		return module.findPage("index");
	}

	public Page doList(WebForm form, Module module) {
		String pdir = CommUtil.null2String(form.get("sid"));
		String nowdir = CommUtil.null2String(form.get("id"));
		String templateFile = Globals.APP_BASE_DIR + File.separator + "WEB-INF"
				+ File.separator + "templates" + File.separator + "htm"
				+ File.separator;
		if(pdir.length()>0){
			templateFile = templateFile + pdir.replace("_spt_", File.separator) + File.separator;
			form.addResult("sid", pdir);
		}
		if(nowdir.length()>0){
			templateFile = templateFile + nowdir + File.separator;
			form.addResult("tid", nowdir);
		}
		File templatePath = new File(templateFile);
		List<Template> tList = new ArrayList<Template>();
		int rows=0;
		int pageSize = 15;
		int currentPage = 1;
		int frontPage = 0;
		int nextPage = currentPage + 1;
		int totalPage=1;
		if (templatePath.exists()) {
			File[] tFiles = templatePath.listFiles();
			Arrays.sort(tFiles, new Comparator<File>(){
				public int compare(File f1, File f2){
					return f1.getName().compareTo(f2.getName());
				}
			});
			rows = tFiles.length;// 分页开始
			totalPage = (int) Math.ceil((float) (rows) / (float) (pageSize));
			int i=0;
			for (File afile : tFiles) {
				Template aTemplate = new Template(afile);
				tList.add(aTemplate);
				i++;
				if(i>pageSize){break;}
			}
		}
		form.addResult("rows", rows);
		form.addResult("pageSize", pageSize);
		form.addResult("frontPage", frontPage);
		form.addResult("currentPage", currentPage);
		form.addResult("nextPage", nextPage);
		form.addResult("totalPage", totalPage);
		form.addResult("tList", tList);
		return module.findPage("list");
	}
	
	public Page doPage(WebForm form, Module module) {
		String pdir = CommUtil.null2String(form.get("sid"));
		String nowdir = CommUtil.null2String(form.get("id"));
		String templateFile = Globals.APP_BASE_DIR + File.separator + "WEB-INF"
				+ File.separator + "templates" + File.separator + "htm"
				+ File.separator;
		if(pdir.length()>0){
			templateFile = templateFile + pdir.replace("_spt_", File.separator) + File.separator;
			form.addResult("sid", pdir);
		}
		if(nowdir.length()>0){
			templateFile = templateFile + nowdir + File.separator;
			form.addResult("tid", nowdir);
		}
		File templatePath = new File(templateFile);
		List<Template> tList = new ArrayList<Template>();
		
		int rows=0;
		int pageSize = 15;
		int currentPage = CommUtil.null2Int(form.get("page"));
		int frontPage = currentPage - 1;
		int nextPage = currentPage + 1;
		int totalPage=1;
		
		if (templatePath.exists()) {
			File[] tFiles = templatePath.listFiles();
			Arrays.sort(tFiles, new Comparator<File>(){
				public int compare(File f1, File f2){
					return f1.getName().compareTo(f2.getName());
				}
			});
			rows = tFiles.length;// 分页开始
			totalPage = (int) Math.ceil((float) (rows) / (float) (pageSize));
			int begin = (currentPage - 1) * pageSize + 1;
			int i=0;
			for (File afile : tFiles) {
				if(i>=(begin-1) && i<(begin+pageSize-1)){
					Template aTemplate = new Template(afile);
					tList.add(aTemplate);
				}
				i++;
				if(i>=(begin+pageSize-1)){break;}
			}
		}
		form.addResult("rows", rows);
		form.addResult("pageSize", pageSize);
		form.addResult("frontPage", frontPage);
		form.addResult("currentPage", currentPage);
		form.addResult("nextPage", nextPage);
		form.addResult("totalPage", totalPage);
		form.addResult("tList", tList);
		return module.findPage("list");
	}
	
	public Page doPrepare(WebForm form, Module module){
		String pdir = CommUtil.null2String(form.get("id"));
		String newFile = CommUtil.null2String(form.get("name"));
		if(pdir.length()>0){
			//Site site=siteDAO.getSiteByTemplate(pdir);
			form.addResult("sitedir", pdir);
		}
		
		form.addResult("name", newFile);
		form.addResult("action", "generate");
		return module.findPage("prepare");
	}
	
	public Page doGenerate(WebForm form, Module module){
		Discoverer dc = (Discoverer)form.toPo(Discoverer.class);
		//String htmlpath=CommUtil.null2String(form.get("name"));
		int ghead = CommUtil.null2Int(form.get("ghead"));
		int gfoot = CommUtil.null2Int(form.get("gfoot"));
		int gleft = CommUtil.null2Int(form.get("gleft"));
		int gtype = CommUtil.null2Int(form.get("gtype"));
		dc.init(ghead,gfoot,gleft,gtype);
		if(dc.generate()){
			form.addResult("msg", "模板生成成功！");
		}else{
			form.addResult("msg", "模板生成失败！");
		}
		return module.findPage("list");
	}
	
	public Page doAdd(WebForm form, Module module) {
		String pdir = CommUtil.null2String(form.get("sid"));
		String nowdir = CommUtil.null2String(form.get("id"));
		String newFile = CommUtil.null2String(form.get("name"));
		form.addResult("name", newFile);
		String tFile = Globals.APP_BASE_DIR + File.separator + "WEB-INF"
				+ File.separator + "templates" + File.separator + "htm"
				+ File.separator;
		String templateFile=tFile;
		if(pdir.length()>0){
			templateFile = templateFile + pdir.replace("_spt_", File.separator) + File.separator;
			form.addResult("sid", pdir);
		}
		if(nowdir.length()>0){
			templateFile = templateFile + nowdir;
			form.addResult("tid", nowdir);
		}
		File templatePath = new File(templateFile);
		if(templatePath.exists()){
			if(templatePath.isDirectory()){
				newFile = templatePath+File.separator+newFile;
			}else{
				newFile = tFile+File.separator+newFile;
			}
			try{
				File newTemplate = new File(newFile);
				if(newTemplate.exists()){
					form.addResult("msg", "文件已存在！");
					return module.findPage("list");
				}else{
					newTemplate.createNewFile();
					org.apache.commons.io.FileUtils.writeStringToFile(newTemplate, "//KnifeCMS模板","UTF-8");
					form.addResult("content", "//KnifeCMS文件");
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return module.findPage("edit");
	}

	public Page doEdit(WebForm form, Module module) {
		String pdir = CommUtil.null2String(form.get("sid"));
		String nowdir = CommUtil.null2String(form.get("id"));
		String name = CommUtil.null2String(form.get("name"));
		String templateFile = Globals.APP_BASE_DIR + File.separator + "WEB-INF"
		+ File.separator + "templates" + File.separator + "htm" + File.separator;
		if(pdir.length()>0){
			templateFile = templateFile + pdir.replace("_spt_", File.separator) + File.separator;
			form.addResult("sid", pdir);
		}
		if(nowdir.length()>0){
			templateFile = templateFile + nowdir + File.separator;
			form.addResult("tid", nowdir);
		}
		String fileContent = "";
		if (name.length() > 0) {
			String path = templateFile + name;
			File tcontent = new File(path);
			try {
				if(tcontent.canWrite()){
					fileContent = org.apache.commons.io.FileUtils.readFileToString(
						tcontent, "UTF-8");
					fileContent = fileContent.replace("&", "&amp;");
					fileContent = fileContent.replace("TEXTAREA","textarea");
					fileContent = fileContent.replace("<textarea", "&lt;textarea");
					fileContent = fileContent.replace("</textarea>", "&lt;/textarea&gt;");
				}else{
					form.addResult("id", name);
					return module.findPage("list");
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			form.addResult("content", fileContent);
		}
		form.addResult("name", name);
		return module.findPage("edit");
	}
	
	public Page doDelete(WebForm form, Module module) {
		String pdir = CommUtil.null2String(form.get("sid"));
		String nowdir = CommUtil.null2String(form.get("id"));
		String name = CommUtil.null2String(form.get("name"));
		String templateFile = Globals.APP_BASE_DIR + "WEB-INF"
		+ File.separator + "templates" + File.separator + "web" + File.separator;
		if(pdir.length()>0){
			templateFile = templateFile + pdir.replace("_spt_", File.separator) + File.separator;
		}
		if(nowdir.length()>0){
			if(!nowdir.equals("null")){
				templateFile = templateFile + nowdir + File.separator;
			}
		}
		//System.out.println("获取到的name是:"+name+",nowdir:"+nowdir);
		if (name.length() > 0) {
			boolean result = false;
			if(name.indexOf(",")>0){
				String[] ids = name.split(",");
				for (int i = 0; i < ids.length; i++) {
					String path = templateFile + ids[i];
					File tcontent = new File(path);
					result = tcontent.delete();
				}
			}else{
				String path = templateFile + name;
				//System.out.println("获取到的路径是:"+path);
				File tcontent = new File(path);
				result = tcontent.delete();
			}
			if(result) {
				form.addResult("msg", "删除成功");
			} else {
				form.addResult("msg", "删除失败");
			}
		}
		return doList(form, module);
	}
	
	public Page doBackup(WebForm form, Module module){
		return null;
	}
	
	public Page doDesign(WebForm form, Module module) {
		return module.findPage("designIndex");
	}
	
	public Page doDesignInfo(WebForm form, Module module) {
		return module.findPage("designInfo");
	}
	
	public Page doDesignEdit(WebForm form, Module module) {
		String pdir = CommUtil.null2String(form.get("sid"));
		String name = CommUtil.null2String(form.get("name"));
		String visualDesign = "<link href=\"/include/manage/ui/portal.css\" type=\"text/css\" rel=\"stylesheet\" />"+
		"<script type=\"text/javascript\" src=\"/include/manage/js/jquery.js\"></script>"+
		"<script type=\"text/javascript\" src=\"/include/manage/js/jquery-ui.js\"></script>"+
		"<script type=\"text/javascript\" src=\"/include/manage/js/portal.js\"></script>"+
		"<script type=\"text/javascript\">"+
		"tName='"+name+"';"+
		"</script>";
		form.addResult("visualDesign", visualDesign);
		form.addResult("name", name);
		return new Page("design",name,"/htm/" + pdir.replace("_spt_", File.separator));
	}
}